var COS = require('../../lib/cos-wx-sdk-v5');
var app = getApp()
Page({

  data: {
    imgList: [],
    imgs: [],
    desc: '',
    cos: '',
    sorts: [],
    curSortId: '',
    index: 0,
    cWidth: '',
    cHeight: ''
  },
  onLoad: function(options) {
    this.data.cos = new COS({
      getAuthorization: function(options, callback) {
        wx.cloud.callFunction({
          name: 'getAuthorization',
          data: {

          },
          success: res => {
            var cosData = res.result.data
            var data = JSON.parse(cosData)
            var credentials = data && data.credentials;
            if (!data || !credentials)
              return console.error('credentials invalid');
            callback({
              TmpSecretId: credentials.tmpSecretId,
              TmpSecretKey: credentials.tmpSecretKey,
              XCosSecurityToken: credentials.sessionToken,
              ExpiredTime: data.expiredTime
            });
          },
          fail: err => {
            console.error('[云函数] [getAuthorization] 调用失败', err)
          }
        })
      },
      Protocol:"https:"
    });
    this.getSorts()

    var time = wx.getStorageSync("time")
    var curTime = new Date().getTime()
    console.log("time ===" + time)
    var timeInt = 0
    if (time) {
      timeInt = parseInt(time)
    }

    console.log("curTime ===" + curTime)
    console.log("timeInt ===" + timeInt)
    console.log("curTime - timeInt===" + (curTime - timeInt))
    var timeNum = parseInt((curTime - timeInt) / (1000 * 60 * 60 * 24))
    console.log("天数=======" + timeNum)
    var accessToken = wx.getStorageSync("access_token")
    console.log("====accessToken===" + accessToken)
    if (timeNum > 28 || !accessToken) {
      this.accessTokenFunc()
    } else {
      this.setData({
        accessToken: accessToken
      })
    }

  },

  bindPicDesc: function(e) {
    this.data.desc = e.detail.value
  },
  PickerChange: function(e) {
    console.log("=====" + JSON.stringify(e))
    var indexStr = e.detail.value
    var index = parseInt(indexStr)
    this.setData({
      curSortId: this.data.sorts[index]._id,
      index:index
    })
  },
  ChooseImage() {
    var that = this
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album'],
      success: (res) => {
        that.onCheckImg(res.tempFilePaths[0])
      }
    });
  },
  accessTokenFunc: function() {
    var that = this
    wx.cloud.callFunction({
      name: 'baiduAccessToken',
      success: res => {
        console.log("==baiduAccessToken==" + JSON.stringify(res))
        that.data.accessToken = res.result.data.access_token
        wx.setStorageSync("access_token", res.result.data.access_token)
        wx.setStorageSync("time", new Date().getTime())
      },
      fail: err => {
        wx.clearStorageSync("access_token")
        wx.showToast({
          icon: 'none',
          title: '调用失败,请重新尝试',
        })
        console.error('云函数baiduAccessToken调用失败：', err)
      }
    })
  },
  // 使用百度鉴黄
  onCheckImg: function(path) {
    var url = "https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined?access_token="
    var that = this
    wx.getFileSystemManager().readFile({
      filePath: path,
      encoding: "base64",
      success: res => {
        var token = wx.getStorageSync("access_token")
        app.request.req(url + token, {
          "image": res.data
        }, function(res) {
          wx.hideLoading()
          var code = res.data.err_code
          if (!code) {
            var result = res.data.conclusionType
            if (result == 1) {
              app.showToastMsg("鉴定合格")
              that.data.imgList.push(path)
              that.setData({
                imgList: that.data.imgList
              })
              that.Upload()
            } else {
              app.showToastMsg("有不良图片")
            }
          } else {
            if (code == 111 || code == 100 || code == 110) {
              wx.clearStorageSync("access_token")
              wx.clearStorageSync("time")
              that.accessTokenFunc()
              return
            }
          }
        }, "POST")
      },
      fail: res => {
        wx.hideLoading()
      }
    })
  },

  Upload() {
    wx.showLoading({
      title: '上传中',
    })
    var that = this
    var length = this.data.imgList.length
    var path = this.data.imgList[length - 1]
    var time = new Date().getTime()
    var randomStr=this.randomCode(6,'0123456789qwertyuiopasdfghjklzxcvbnm')
    this.data.cos.postObject({
      Bucket: 'xiaojiejie-1253624714',
      Region: 'ap-shanghai',
      Key: 'upload/' + time + randomStr +".png",
      FilePath: path,
      Protocol: "https:",
      ACL: "public-read",
      onProgress: function(info) {
        console.log("=====" + JSON.stringify(info));
      }
    }, function(err, data) {
      wx.hideLoading()
      console.log("=====" + JSON.stringify(data));
      var url = "https://" + data.Location
      console.log("url=====" + url);
      if (!err) {
        that.data.imgs.push(url)
      }
    });


  },

  randomCode(len, dict) {
    for (var i = 0, rs = ''; i < len; i++)
      rs += dict.charAt(Math.floor(Math.random() * 100000000) % dict.length);
    return rs;
  },
  ViewImage(e) {
    wx.previewImage({
      urls: this.data.imgList,
      current: e.currentTarget.dataset.url
    });
  },
  DelImg(e) {
    var that = this
    wx.showModal({
      title: '删除图片',
      content: '确定要删除这张图片吗？',
      cancelText: '再看看',
      confirmText: '再见',
      success: res => {
        if (res.confirm) {
          that.data.imgList.splice(e.currentTarget.dataset.index, 1);
          that.data.imgs.splice(e.currentTarget.dataset.index, 1);
          that.setData({
            imgList: that.data.imgList,
            imgs: that.data.imgs
          })
        }
      }
    })
  },
  onSubmit: function() {
    if (this.data.desc == "") {
      app.showToastMsg("请输入描述文案")
      return
    }
    if (this.data.curSortId == "") {
      this.data.curSortId = this.data.sorts[0]._id
    }
    if (this.data.curSortId == "") {
      app.showToastMsg("请选择分类")
      return
    }
    if (this.data.imgs.length == 0) {
      app.showToastMsg("请添加图片")
      return
    }

    var that = this
    app.request.reqCloudLoading("uploadPic", {
      desc: this.data.desc,
      imgs: this.data.imgs,
      sortId: this.data.curSortId
    }, function(res) {
      console.log("====" + JSON.stringify(res))
      if (res.code == 0) {
        that.setData({
          imgs: [],
          imgList: [],
          desc: ""
        })
      } else {
        app.showToastMsg(res.msg)
      }
    })
  },
  getSorts: function() {
    var that = this
    app.request.reqCloudLoading("getSorts", {},
      function(res) {
        console.log("====" + JSON.stringify(res))
        if (res.code == 0) {
          console.log("=res.data===" + JSON.stringify(res.data))
          that.setData({
            sorts: res.data,
          })
        } else {
          app.showToastMsg(res.msg)
        }
      })
  }
})